package com.lm.activiti.boot.tools;

import com.itextpdf.html2pdf.ConverterProperties;
import com.itextpdf.html2pdf.HtmlConverter;
import com.itextpdf.html2pdf.attach.impl.DefaultTagWorkerFactory;
import com.itextpdf.html2pdf.resolver.font.DefaultFontProvider;
import com.itextpdf.layout.font.FontProvider;

import java.io.*;

/**
 * @author lm_jcf
 * @date 2019/7/8 14:03
 */
public class ITextConvertPDFUtils {

    public static void convertHandle(String htmlPath, String pdfPath) throws IOException {
        HtmlConverter.convertToPdf(new File(htmlPath), new File(pdfPath), installPDFPro());
    }

    public static void main(String[] args) throws IOException {
        ITextConvertPDFUtils pdfUtils = new ITextConvertPDFUtils();
        File rootFile = new File(pdfUtils.getClass().getResource("").getPath());
        String path = rootFile.getParentFile().getParentFile().getParentFile().getParentFile().getParentFile().getPath();


//        String originUrl = "htmlConvertPdf.html";
//        String originUrl = path + "\\html\\test.html";
//        String originUrl = path + "\\html\\teststs.html";
        String originUrl = path + "\\html\\teststs2.html";


        String targetUrl = path + "\\htmlConvertPdfV2.pdf";
        convertHandle(originUrl, targetUrl);
//        convertHandleText(targetUrl);
        System.out.println("OK");
    }

    public static ConverterProperties installPDFPro() {
        ConverterProperties props = new ConverterProperties();
        DefaultFontProvider defaultFontProvider = new DefaultFontProvider(false, false, false);

        String path = props.getClass().getClassLoader().getResource("simhei.ttf").getPath();
        defaultFontProvider.addFont(path);
        props.setFontProvider(defaultFontProvider);

        FontProvider fp = new FontProvider();
        fp.addStandardPdfFonts();

        props.setFontProvider(fp);
        props.setCharset("UTF-8");
        DefaultTagWorkerFactory tagWorkerFactory = new DefaultTagWorkerFactory();
        props.setTagWorkerFactory(tagWorkerFactory);

        return props;
    }

    public static void convertHandleText(String pdfPath) throws IOException {
        String html = "<html><body><p>这个有谁改过没上传完整的么？\n</p></body></html>";

        File pdfFile = new File(pdfPath);
        if (!pdfFile.exists()) {
            pdfFile.getParentFile().mkdirs();
        }


        HtmlConverter.convertToPdf(html, new FileOutputStream(pdfFile),installPDFPro());
    }

}
